# -*- coding: utf-8 -*-
"""
@Time： 2023/12/20 16:20
@Auth： gubei
@File： init_admin.py
@IDE：PyCharm
@Description：初始化数据库，创建超级管理员账号和角色
"""
import sys
import os
from pathlib import Path

# 将项目根目录添加到Python路径中
script_dir = Path(__file__).resolve().parent
project_root = script_dir.parent
sys.path.append(str(project_root))

from sqlalchemy.orm import Session
from sqlalchemy import inspect
from core.db.database import get_db, engine
from core.models.models import Base, User, Role, Permission
from core.auth.oauth2 import get_password_hash
from api.user.serializers import UserRole
from sqlalchemy.sql import text


def init_database(force_recreate=False):
    """初始化数据库表结构
    
    Args:
        force_recreate (bool): 是否强制重新创建表，默认为False
    """
    print("正在初始化数据库表...")
    # 检查数据库表是否已存在
    inspector = inspect(engine)
    tables_exist = inspector.has_table('users') and inspector.has_table('roles') and inspector.has_table('permissions')
    
    if force_recreate and tables_exist:
        print("正在删除已存在的表...")
        # 使用SQL直接删除表，避免外键约束问题
        with engine.connect() as conn:
            # 使用正确的方式执行原始SQL
            conn.execute(text("SET FOREIGN_KEY_CHECKS = 0"))
            conn.execute(text("DROP TABLE IF EXISTS users"))
            conn.execute(text("DROP TABLE IF EXISTS permissions"))
            conn.execute(text("DROP TABLE IF EXISTS roles"))
            conn.execute(text("SET FOREIGN_KEY_CHECKS = 1"))
            conn.commit()
        print("表已删除.")
        tables_exist = False
    
    if not tables_exist:
        Base.metadata.create_all(bind=engine)
        print("数据库表初始化完成。")
    else:
        print("数据库表已存在，跳过初始化。")


def create_roles(db: Session):
    """创建基本角色"""
    print("正在检查并创建角色...")
    
    # 超级管理员权限菜单
    admin_permissions = [
        {
            "id": 1,
            "title": "系统管理",
            "icon": "SettingOutlined",
            "path": "/system",
            "children": [
                {"id": 101, "title": "用户管理", "path": "/system/user"},
                {"id": 102, "title": "角色管理", "path": "/system/role"},
                {"id": 103, "title": "日志管理", "path": "/system/log"}
            ]
        },
        {
            "id": 2,
            "title": "仪表盘",
            "icon": "DashboardOutlined",
            "path": "/dashboard",
            "children": [
                {"id": 201, "title": "分析页", "path": "/dashboard/analysis"},
                {"id": 202, "title": "监控页", "path": "/dashboard/monitor"},
                {"id": 203, "title": "工作台", "path": "/dashboard/workplace"}
            ]
        }
    ]
    
    # 普通管理员权限菜单
    staff_permissions = [
        {
            "id": 2,
            "title": "仪表盘",
            "icon": "DashboardOutlined",
            "path": "/dashboard",
            "children": [
                {"id": 201, "title": "分析页", "path": "/dashboard/analysis"},
                {"id": 203, "title": "工作台", "path": "/dashboard/workplace"}
            ]
        }
    ]
    
    # 普通用户权限菜单
    user_permissions = [
        {
            "id": 2,
            "title": "仪表盘",
            "icon": "DashboardOutlined",
            "path": "/dashboard",
            "children": [
                {"id": 203, "title": "工作台", "path": "/dashboard/workplace"}
            ]
        }
    ]
    
    # 检查角色是否已存在
    super_admin_role = db.query(Role).filter_by(name=UserRole.super_admin).first()
    admin_role = db.query(Role).filter_by(name=UserRole.admin).first()
    user_role = db.query(Role).filter_by(name=UserRole.user).first()
    
    # 创建超级管理员角色
    if not super_admin_role:
        super_admin_role = Role(name=UserRole.super_admin)
        db.add(super_admin_role)
        db.flush()  # 刷新会话以获取生成的ID
        
        # 添加权限
        super_admin_permission = Permission(
            content=str(admin_permissions),
            role_id=super_admin_role.id
        )
        db.add(super_admin_permission)
        print(f"已创建超级管理员角色 (ID: {super_admin_role.id})")
    else:
        print(f"超级管理员角色已存在 (ID: {super_admin_role.id})")
    
    # 创建管理员角色
    if not admin_role:
        admin_role = Role(name=UserRole.admin)
        db.add(admin_role)
        db.flush()
        
        # 添加权限
        admin_permission = Permission(
            content=str(staff_permissions),
            role_id=admin_role.id
        )
        db.add(admin_permission)
        print(f"已创建管理员角色 (ID: {admin_role.id})")
    else:
        print(f"管理员角色已存在 (ID: {admin_role.id})")
    
    # 创建普通用户角色
    if not user_role:
        user_role = Role(name=UserRole.user)
        db.add(user_role)
        db.flush()
        
        # 添加权限
        user_permission = Permission(
            content=str(user_permissions),
            role_id=user_role.id
        )
        db.add(user_permission)
        print(f"已创建普通用户角色 (ID: {user_role.id})")
    else:
        print(f"普通用户角色已存在 (ID: {user_role.id})")
    
    db.commit()
    return super_admin_role, admin_role, user_role


def create_super_admin(db: Session, super_admin_role_id: int):
    """创建超级管理员用户"""
    print("正在检查并创建超级管理员账号...")
    
    # 检查管理员是否已存在
    admin_user = db.query(User).filter_by(userName="superadmin").first()
    if admin_user:
        print(f"超级管理员 'superadmin' 已存在，ID: {admin_user.id}")
        return admin_user
    
    # 创建超级管理员
    hashed_password = get_password_hash("admin123")
    admin_user = User(
        userName="superadmin",
        nickName="超级管理员",
        userPwd=hashed_password,
        role_id=super_admin_role_id,
        isActive=1
    )
    
    db.add(admin_user)
    db.commit()
    print(f"已创建超级管理员 'superadmin'，ID: {admin_user.id}，初始密码: admin123")
    return admin_user


def main():
    """主函数"""
    print("开始初始化系统...")
    
    # 获取命令行参数
    import sys
    force_recreate = "--force" in sys.argv
    
    # 初始化数据库表
    init_database(force_recreate)
    
    # 获取数据库会话
    db = next(get_db())
    try:
        # 创建角色
        super_admin_role, admin_role, user_role = create_roles(db)
        
        # 创建超级管理员用户
        admin_user = create_super_admin(db, super_admin_role.id)
        
        # 获取角色名称
        role_name = db.query(Role).filter_by(id=admin_user.role_id).first().name
        
        print("\n初始化完成!")
        print("=" * 50)
        print("超级管理员账号信息:")
        print(f"用户名: superadmin")
        print(f"密码: admin123")
        print(f"角色: {role_name}")
        print(f"角色ID: {super_admin_role.id}")
        print("=" * 50)
        print("请登录后立即修改默认密码!")
    except Exception as e:
        db.rollback()
        print(f"初始化失败: {str(e)}")
    finally:
        db.close()


if __name__ == "__main__":
    main() 